package com.thomas.sharing.mybatis.config;

import java.io.IOException;

import javax.sql.DataSource;

import org.flywaydb.core.Flyway;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.zaxxer.hikari.HikariDataSource;

@Configuration
@EnableConfigurationProperties
@MapperScan("com.thomas.sharing.mybatis.mapper")
public class DatasourceConfig {
	
	
/*	@Bean
	@Primary
	@ConfigurationProperties("spring.datasource")
	public DataSource dataSource(){
		return DataSourceBuilder.create().build();
	}*/
	
	@Bean
	@Primary
	@ConfigurationProperties(prefix="spring.datasource")
	public DataSourceProperties dataSourceProperties(){
		return new DataSourceProperties();
	}
	
	@Bean
	public DataSource initDataBase(){
		//return DataSourceBuilder.create().build();
		DataSourceProperties dataSourceProperties = dataSourceProperties();
		DataSource dataSource = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
		return dataSource;
	}			
	
	
	@Bean("propertyFlyway")
	@ConfigurationProperties("spring.flyway")
	public Flyway flyway(){
		return new Flyway();
	}
	
	@Bean("flyway")
	@Primary
	public Flyway initFlyway(){
		Flyway flyway = flyway();
		flyway.setDataSource(initDataBase());
		flyway.migrate();
		return flyway;
	}
	
	@Bean
	public SqlSessionFactoryBean sqlSessionFactoryBean() throws IOException{
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		//set datasource
		sqlSessionFactoryBean.setDataSource(initDataBase());
		//set mapper location
		PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
		sqlSessionFactoryBean.setMapperLocations(resourceResolver.getResources("classpath:/entity/map/**/*map.xml"));
		//set Aliases package
		sqlSessionFactoryBean.setTypeAliasesPackage("com.thomas.sharing.mybatis.model");		
		return sqlSessionFactoryBean;
	}
	
/*    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
      return sqlSessionFactoryBean().getObject();
    }*/

/*    @Bean
    public CarMapper carMapper() throws Exception {
      SqlSessionTemplate sessionTemplate = new SqlSessionTemplate(sqlSessionFactory());
      CarMapper carMapper = sessionTemplate.getMapper(CarMapper.class);
      return carMapper;
    }*/
}
